/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package net.worlds.object;

import java.awt.Color;
import java.awt.Graphics;
import java.util.ArrayList;
import net.worlds.WorldsException;
import net.worlds.Main;
import org.jbox2d.common.Vec2D;
import org.jbox2d.dynamics.Body;


public class Weld extends Joint{
    public Vec2D localAnchor1;
    public Weld() throws WorldsException
    {
        super("Weld");
        //x_;
    }
    @Override
    protected void createJoint() {
        Body oldBody = part1.getBody();
        /*for(Part p : oldBody.getParts())
        {
            Main.getActiveWorld().connect(p, part2, this);
        }
        foPart p : part2.getBody().getParts())
        {
            Main.getActiveWorld().connect(p, part1, this);
        }*/
        part2.merge(part1);
        for(Part other : (ArrayList<Part>) oldBody.parts.clone())
        {
            if(other != part1 && other != part2)
            {
                part2.merge(other);
            }
        }
        oldBody.removeWeld(this);
        part2.getBody().addWeld(this);
        localAnchor1 = new Vec2D(part2.getBody().getLocalPoint(anchor));

    }
    public Vec2D getAnchor1()
    {
        if(part1 != null && part1.getBody() != null && localAnchor1 != null)
            return new Vec2D(part1.getBody().getWorldPoint(localAnchor1));
        else
            return Vec2D.ORIGIN;
    }
    @Override
    public void destructor() throws WorldsException
    {
        super.destructor();
        //Main.getActiveWorld().disconnect(this);
        part2.getBody().removeWeld(this);
        part2.splitAway();
        part1.setTempFixed(false);
        //part2.getBody().validateWelds();
        //part1.getBody().validateWelds();
    }
    @Override
    public void draw(Graphics g) throws WorldsException
    {
        if(disabled || !getBooleanProp("Visible") || part1 == null || part2 == null || localAnchor1 == null || part1.getBody() == null || part1.disabled || part2.disabled)
            return;
        Vec2D screenPos = getAnchor1().worldToScreen(Main.getView()); //!!!
        Color c = getColorProp("Color");
        g.setColor(new Color(c.getRed(), c.getGreen(), c.getBlue(), 127));
        g.fillRect((int) screenPos.x - 5, (int) screenPos.y - 5, 10, 10);
        if(selected)
        {
            g.setColor(Color.white);
            g.drawRect((int) screenPos.x - 5, (int) screenPos.y - 5, 10, 10);
        }
    }

}
